/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.depsea.oss.client.minio;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.depsea.oss.client.CustomerBucketOssTemplate;
import org.depsea.oss.client.OssType;
import org.depsea.oss.exception.OssException;
import org.depsea.oss.filter.FileUploadFilter;
import org.depsea.oss.model.FileInfo;
import org.depsea.oss.model.FileStreamInfo;
import org.depsea.oss.strategy.FilenameHandleStrategy;
import org.depsea.oss.strategy.OriginalFilenameHandleStrategyImpl;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Bucket 文件处理
 *
 * @author Wang Chengwei
 * @since 1.0.0 2021/12/1 17:33
 */
@Slf4j
public class MinioCustomerBucketOssTemplate extends AbstractMinioOssTemplate implements CustomerBucketOssTemplate {

    private boolean autoCreateBucket = true;

    private final List<FileUploadFilter> filters = new ArrayList<>();

    private FilenameHandleStrategy filenameHandleStrategy = new OriginalFilenameHandleStrategyImpl();

    public MinioCustomerBucketOssTemplate(MinioClient minioClient) {
        super(minioClient);
    }

    public void setFilenameHandleStrategy(FilenameHandleStrategy filenameHandleStrategy) {
        this.filenameHandleStrategy = filenameHandleStrategy;
    }

    public void addFilters(List<FileUploadFilter> filters) {
        if (!CollectionUtils.isEmpty(filters)) {
            this.filters.addAll(filters);
        }
    }

    public void addFilters(FileUploadFilter filter) {
        this.filters.add(filter);
    }

    public void setAutoCreateBucket(boolean autoCreateBucket) {
        this.autoCreateBucket = autoCreateBucket;
    }

    @Override
    public FileInfo upload(String bucketName, String folder, String filename, String originalFilename, String contentType, InputStream ins) {
        this.checkBucketAndCreate(bucketName);
        return this.doUpload(bucketName, folder, filename, originalFilename, contentType, ins);
    }

    @Override
    public FileStreamInfo get(String bucketName, String fullPath) {
        this.checkBucket(bucketName);
        return this.doGet(bucketName, fullPath);
    }

    @Override
    public void download(String bucketName, String fullPath, HttpServletResponse response) {
        this.checkBucket(bucketName);
        this.doDownload(bucketName, fullPath, response);
    }

    @Override
    public void download(String bucketName, String fullPath, String filename, HttpServletResponse response) {
        this.checkBucket(bucketName);
        this.doDownload(bucketName, fullPath, filename, response);
    }

    @Override
    public void preview(String bucketName, String fullPath, HttpServletResponse response) {
        this.checkBucket(bucketName);
        this.doPreview(bucketName, fullPath, response);
    }

    @Override
    public FilenameHandleStrategy getFilenameHandleStrategy() {
        return this.filenameHandleStrategy;
    }

    @Override
    protected List<FileUploadFilter> getFilters() {
        return this.filters;
    }

    @Override
    protected String getOssTypeName() {
        return OssType.MINIO.name();
    }

    @Override
    public void delete(String bucketName, String ossKey) {
        this.deleteObject(bucketName, ossKey);
    }

    private void checkBucket(String bucketName) {
        // 创建默认Bucket
        try {
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build();

            if (!minioClient.bucketExists(bucketExistsArgs)) {
                throw new OssException("Bucket 不存在");
            }
        } catch (OssException e) {
            throw e;
        } catch (Exception e) {
            throw new OssException("无法校验Bucket", e);
        }
    }

    private void checkBucketAndCreate(String bucketName) {
        // 创建默认Bucket
        try {
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build();
            if (!minioClient.bucketExists(bucketExistsArgs)) {
                if (this.autoCreateBucket) {
                    minioClient.makeBucket(
                            MakeBucketArgs.builder()
                                    .bucket(bucketName)
                                    .build()
                    );
                    log.info("已创建Bucket：[" + bucketName + "]");
                } else {
                    throw new OssException("Bucket 不存在");
                }

            }
        } catch (OssException e) {
            throw e;
        }  catch (Exception e) {
            throw new OssException("无法校验Bucket", e);
        }
    }
}
